const request = require('request');
const mongoose = require('mongoose');
const BooksSchema = mongoose.model('BooksSchema');
const UserSchema = mongoose.model('UserSchema');
const Router = require('koa-router');
const BooksRouter = new Router();

function getBookInfo (api) {
  return new Promise((resolve, reject) => {
    request.get(api, (err, _, body) => {
      if (err) {
        reject(err);
      } else {
        resolve(body);
      }
    });
  })
}

// 扫码添加图书
BooksRouter.get('/saveBookInfo', async ctx => {
  try {
    const { isbnCode, openId } = ctx.request.query;
    const res = await BooksSchema.find({ isbnCode }).exec();
    if (res.length) {
      return ctx.body = {
        code: 500,
        data: '该书已经添加',
      }
    }
    const isbnApi = `https://api.douban.com/v2/book/isbn/${isbnCode}?apikey=0df993c66c0c636e29ecbb5344252a4a`;
    const bookInfo = await getBookInfo(isbnApi);
    const data = JSON.parse(bookInfo);
    if (data.title) {
      const user = await UserSchema.findOne({ openId }).exec();
      const { rating, title, image, alt, publisher, summary, price, tags = [], author = [] } = data;
      const avrgRating = rating.average;
      const formatTags = tags.map(tag => `${tag.title} ${tag.count}`);
      await new BooksSchema({
        isbnCode,
        userId: user._id,
        title,
        image,
        alt,
        publisher,
        summary,
        price,
        author,
        avrgRating,
        formatTags,
      }).save();
      return ctx.body = {
        code: 200,
        data: `添加<${title}>成功`,
      }
    }
    ctx.body = {
      code: 500,
      data: data.msg
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
});

// 获取轮播图浏览量的前9名
BooksRouter.get('/getSwiper', async ctx => {
  try {
    const res = await BooksSchema.find().sort({ accessCount: -1 }).limit(9).exec();
    ctx.body = {
      code: 200,
      data: res,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
});

// 获取图书列表
BooksRouter.get('/getList', async ctx => {
  try {
    const pageSize = 8;
    const { page } = ctx.request.query;
    const skipCount = (page - 1) * pageSize;
    const totalCount = await BooksSchema.find().countDocuments().exec();
    const booksList = await BooksSchema.find()
    .populate({ // 连表查询
      path: 'userId', // 对应UserSchema的_id主键字段
      select: { nickName: 1, _id: 0 }
    })
    .limit(pageSize)
    .skip(skipCount)
    .exec(); // 没有会返回[]
    ctx.body = {
      code: 200,
      data: {
        pageSize,
        page,
        total: totalCount,
        list: booksList,
      },
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
})

BooksRouter.get('/getDetail', async ctx => {
  try {
    const { isbnCode } = ctx.request.query;
    const res = await BooksSchema.findOne({ isbnCode }).populate({
      path: 'userId',
      select: { nickName: 1, avatarUrl: 1, _id: 0 }
    }).exec();
    res.accessCount += 1; // 访问数量+1
    await BooksSchema.updateOne({ isbnCode }, { $set: { accessCount: res.accessCount } }); // 更新访问量
    ctx.body = {
      code: 200,
      data: res,
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
})

module.exports = BooksRouter;